package com.tigercel.xiangchengyun.ui.fragments

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jcodecraeer.xrecyclerview.XRecyclerView
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.tigercel.xiangchengyun.R
import com.tigercel.xiangchengyun.adapter.NewsBannerAdapter
import com.tigercel.xiangchengyun.adapter.NewsReportAdapter
import com.tigercel.xiangchengyun.entity.Banner
import com.tigercel.xiangchengyun.entity.NewsReportBean
import com.tigercel.xiangchengyun.ui.activities.ConvenientPeopleDetailsActivity
import com.tigercel.xiangchengyun.ui.custom.lbanners.LMBanners
import com.tigercel.xiangchengyun.ui.custom.lbanners.transformer.TransitionEffect
import com.tigercel.xiangchengyun.utils.Global
import com.tigercel.xiangchengyun.utils.JsonUtil
import com.tigercel.xiangchengyun.utils.PreferencesUtil
import kotlinx.android.synthetic.main.fragment_news_special.*
import org.jetbrains.anko.support.v4.toast
import java.text.SimpleDateFormat

class NewsReportFragment : Fragment() {
    companion object {

        fun newInstance(channelPosition: Int): NewsReportFragment? {
            val fragment = NewsReportFragment()
            val bundle = Bundle()
            bundle.putInt("channelPosition", channelPosition)
            fragment.arguments = bundle
            return fragment
        }
    }

    private var intoCount = 0
    private var containerView: View? = null
    private var banner: LMBanners<Any>? = null
    private var headBanner: View? = null
    private var channelPosition: Int = 0
    private var contentList: MutableList<NewsReportBean>? = null
    private var isHandle: Boolean = false
    private var banners1: MutableList<Banner>? = null
    private var newsAdapter: NewsReportAdapter? = null
    private var global_model_name: String? = null
    private var localDatas: PreferencesUtil? = null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        containerView = inflater.inflate(R.layout.fragment_news_special, container, false)
        if (arguments != null)
            channelPosition = arguments!!.getInt("channelPosition")

        return containerView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerview.layoutManager = LinearLayoutManager(activity)
        recyclerview.refresh()
        headBanner = View.inflate(activity, R.layout.banners, null)
        banner = headBanner?.findViewById(R.id.banners)
        banner!!.setIndicatorBottomPadding(8)
        banner!!.setHoriZontalTransitionEffect(TransitionEffect.Default)
        banners1 = ArrayList()
        contentList = ArrayList()

//        getContent("create")
        newsAdapter = NewsReportAdapter(ArrayList()) {
            val intent = Intent()
            intent.putExtra("content_id", it.content_id)
            if (it.model_name != "") {
                intent.putExtra("model_name", it.model_name)
            } else {
                intent.putExtra("model_name", it.author)
            }
            intent.putExtra("isHandle", it.isHandle)
            intent.putExtra("model", it.model)
            intent.putExtra("viewtimes", it.lookUp)
            intent.setClass(activity, ConvenientPeopleDetailsActivity::class.java)
            startActivity(intent)
        }
        recyclerview.adapter = newsAdapter
    }

    override fun onDestroy() {
        super.onDestroy()
        banner!!.clearImageTimerTask()
    }

    private fun getContent(type: String) {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm")
        OkGo.get<String>(Global.baseUrl + Global.commonUrl)
                .tag(activity)
                .params("channel_id", channelPosition)
                .params("device_code", Global.getDeviceId())
                .params("user_id", localDatas!!.preferences["user_id"])
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val content = response!!.body()
                        val status = JsonUtil.get_key_string("status", content!!)
                        var msg = JsonUtil.get_key_string("msg", content)
                        val code = JsonUtil.get_key_string("code", content)
                        val data = JsonUtil.get_key_string("data", content)
                        var model = JsonUtil.get_key_string("model", data)
                        global_model_name = model
                        var show_type = JsonUtil.get_key_string("show_type", data)
                        val banner1 = JsonUtil.getList("banner", data)
                        val conent = JsonUtil.getList("content", data)
                        if (status == "0") {
                            if (banner1.isNotEmpty()) {
                                for (i in 0 until banner1.size) {
                                    val title1 = JsonUtil.get_key_string("title", banner1[i])
                                    val img = JsonUtil.get_key_string("img", banner1[i])
                                    var des = JsonUtil.get_key_string("des", banner1[i])
                                    var contact = JsonUtil.get_key_string("contact", banner1[i])
                                    val bannerBean = Banner(0, title1, img, "")
                                    banners1!!.add(bannerBean)

                                }
                                banner!!.setAdapter(NewsBannerAdapter(activity), banners1 as List<Any>?)
                                if (type.equals("create") && intoCount == 0) {
                                    recyclerview.addHeaderView(headBanner)
                                }


                            }
                            if (conent.isNotEmpty()) {
                                for (i in 0 until conent.size) {
                                    val content_id = JsonUtil.get_key_string("content_id", conent[i])
                                    val title = JsonUtil.get_key_string("title", conent[i])
                                    val model1 = JsonUtil.get_key_string("model", conent[i])
                                    val model_name = JsonUtil.get_key_string("model_name", conent[i])
                                    val snap_img = JsonUtil.getList("snap_img", conent[i])
                                    val pub_time = JsonUtil.get_key_string("pub_time", conent[i]).toLong()
                                    val state = JsonUtil.get_key_string("state", conent[i])
                                    val d = sdf.format(pub_time * 1000L)
                                    isHandle = state != "0"
                                    var news = NewsReportBean(content_id, 0, title, global_model_name!!, "", d, 231, snap_img, 265, isHandle, model1, model_name)
                                    contentList!!.add(news)
                                }
                                newsAdapter!!.addAll(contentList!!)
                                recyclerview.setLoadingListener(object : XRecyclerView.LoadingListener {
                                    override fun onRefresh() {
                                        newsAdapter!!.clear()
                                        banners1!!.clear()
                                        contentList!!.clear()
                                        getContent("refresh")

                                    }

                                    override fun onLoadMore() {
                                        getMoreContent()
                                    }
                                })
                            } else {
                                toast(getString(R.string.listNoData))
                            }
                            recyclerview.refreshComplete()
                            intoCount++
                        } else {
                            toast(getString(R.string.readFaile))
                        }
                    }
                })
    }

    private fun getMoreContent() {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm")
        OkGo.get<String>(Global.baseUrl + "v1/channel/content/page")
                .tag(this)
                .params("channel_id", channelPosition)
                .params("device_code", Global.getDeviceId())
                .params("page_size", "10")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val content = response!!.body()
                        val status = JsonUtil.get_key_string("status", content!!)
                        val msg = JsonUtil.get_key_string("msg", content!!)
                        val code = JsonUtil.get_key_string("code", content!!)
                        val data = JsonUtil.getList("data", content!!)
                        if (status == "0") {
                            var news: MutableList<NewsReportBean>
                            news = ArrayList()
                            if (data.isNotEmpty()) {
                                for (i in 0 until data.size) {
                                    val content_id = JsonUtil.get_key_string("content_id", data[i])
                                    val title = JsonUtil.get_key_string("title", data[i])
                                    val model = JsonUtil.get_key_string("model", data[i])
                                    val model_name = JsonUtil.get_key_string("model_name", data[i])
                                    val snap_img = JsonUtil.getList("snap_img", data[i])
                                    val pub_time = JsonUtil.get_key_string("pub_time", data[i]).toLong()
                                    val state = JsonUtil.get_key_string("state", data[i])
                                    val d = sdf.format(pub_time * 1000L)
                                    isHandle = state != "0"
                                    var news1 = NewsReportBean(content_id, 1, title, global_model_name!!, "", d, 0, snap_img, 100, isHandle, model, model_name)
                                    news.add(news1)
                                }
                                newsAdapter!!.addAll(news)

                            } else {
                                recyclerview.setFootViewText(getString(R.string.alreadyloadall), "")
                            }
                            recyclerview.loadMoreComplete()
                        } else {
                            toast(getString(R.string.readFaile))
                        }
                    }
                })
    }

    override fun onResume() {
        super.onResume()
        localDatas = PreferencesUtil(activity)
        recyclerview.refresh()
        getContent("create")
    }
}
